import React, { useState } from "react";
import { Button, Input, Modal, Upload } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { postUploadApi, postUploadUserApi } from "../../api/user";
import { successMsg } from "../../utils/message";
import { useDispatch, useSelector } from "react-redux";
import type { RootState } from "../../store";
import { changeAvatar, changeToken, changeUser } from "../../store/user";

interface UploadFile {
  uid: string;
  name: string;
  status?: "uploading" | "done" | "error" | "removed";
  url?: string;
  // 其他可能的属性
}
const Bloa = () => {
  const [fileList, setFileList] = useState<UploadFile[]>([]);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [previewImage, setPreviewImage] = useState("");
  const [username, setUserName] = useState("")
  const users = useSelector((state: RootState ) => state.user)
  const dispath = useDispatch()

  const props = {
    action: "https://660d2bd96ddfa2943b33731c.mockapi.io/api/upload",
    onPreview: (file) => {
      handlePreview(file);
    },
    onRemove: () => {
      // 使用 setFileList 替代 this.setState
      setFileList([]);
    },
    customRequest: async (val) => {
      const format = new FormData();
      format.append("file", val.file);
      const res = await postUploadApi(format);
      console.log(res);

      successMsg("上传成功");
      val.file.status = "done";
      val.file.url = "http://127.0.0.1:3000" + res.path;
      // 执行这句后，图片列表可以看到有图片了
      setFileList([val.file]);
    },
    fileList, // upload 必不可少的属性
  };

  const handlePreview = async (file) => {
    // 如果文件没有url但有originFileObj，则创建临时URL
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj);
    }
    setPreviewImage(file.url || file.preview);
    setPreviewVisible(true);
  };

  const getBase64 = (file) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.readAsDataURL(file);
      reader.onload = () => resolve(reader.result);
      reader.onerror = (error) => reject(error);
    });
  };

  const submit = async () => {
    const form = {
      username: username,
      avatar: fileList[0].url as string,
      id: users.userInfo?.id
    } 
    const res = await postUploadUserApi(form)
    dispath(changeAvatar({avatar: res.avatar}))
    dispath(changeUser({username: res.username}))
    successMsg('修改成功')
  }

  const uploadButton = (
    <button style={{ border: 0, background: "none" }} type="button">
      <PlusOutlined />
      <div style={{ marginTop: 8 }}>Upload</div>
    </button>
  );

  return (
    <div>
      <div style={{ width: '200px', marginBottom: '10px' }}>
        用户名: <Input placeholder="Basic usage" value={username} onChange={(e) => {
          setUserName(e.target.value)
        }}/>
      </div>
      <Upload {...props} listType="picture-card">
        {fileList.length >= 8 ? null : uploadButton}
      </Upload>
      <Modal
        visible={previewVisible}
        footer={null}
        onCancel={() => setPreviewVisible(false)}
      >
        <img alt="预览" style={{ width: "100%" }} src={previewImage} />
      </Modal>

      <Button style={{ marginTop: 10 }} onClick={() => {
        submit()
      }}>修改</Button>
    </div>
  );
};

export default Bloa;
